package com.example.mongo.controller;

import com.example.mongo.Article;
import com.example.mongo.VerificationCode;
import com.example.mongo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Create By: 乔一 https://www.joejay.cn
 * Create In: 2018-01-16 16:40
 */
@RestController
@RequestMapping("/Article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping(method = RequestMethod.POST)
    public void save(Article article){
        articleService.save(article);
    }

    @RequestMapping(value = "/{page}/{size}", method = RequestMethod.GET)
    public Page<Article> findByKey(String key,@PathVariable Integer page,@PathVariable Integer size){
        Page<Article> articlePage = articleService.findByKey(key,page,size);
        return articlePage;
    }

    @RequestMapping
    public void createCode(HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 自定义宽、高、字数和干扰线的条数
        VerificationCode code = new VerificationCode(100, 30, 4, 10);
        // 存入session
        HttpSession session = request.getSession();
        session.setAttribute("code", code.getCode());
        // 响应图片
        ServletOutputStream out = response.getOutputStream();
        code.write(out);
    }



}
